package com.atguigu.yygh.user.service.impl;

import com.atguigu.yygh.common.config.YyghException;
import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.mapper.PatientMapper;
import com.atguigu.yygh.user.mapper.UserInfoMapper;
import com.atguigu.yygh.user.service.PatientService;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.utils.AuthContextHolder;
import com.atguigu.yygh.utils.JwtHelper;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserAuthVo;
import com.atguigu.yygh.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author DongYu Zhou
 * @date 2022/6/29 21:38
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private PatientService patientService;

    /**
     * <img src="https://yygh20220212.oss-cn-beijing.aliyuncs.com/235918-1630079958392e.jpg">
     *
     * @param loginVo
     * @return
     */
    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        //1取出参数、验空
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        String openid = loginVo.getOpenid();
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new YyghException(20001, "登录信息有误");
        }
        //2 校验验证码
        //2.1从redis获取验证码
        String redisCode = redisTemplate.opsForValue().get(phone);
        //2.2校验验证码
        if (!code.equals(redisCode)) {
            throw new YyghException(20001, "验证码有误");
        }
        Map<String, Object> map = new HashMap<>();
        //2.5 验证openid,确认是手机号验证码登录、绑定手机号
        if (StringUtils.isEmpty(openid)) {
            //3根据手机号查询用户信息
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("phone", phone);
            UserInfo userInfo = baseMapper.selectOne(wrapper);
            //4用户为空实现注册流程
            if (userInfo == null) {
                userInfo = new UserInfo();
                userInfo.setPhone(phone);
                userInfo.setName("");
                userInfo.setStatus(1);
                baseMapper.insert(userInfo);
            }
            //5校验用户是否被锁定
            if (userInfo.getStatus() == 0) {
                throw new YyghException(20001, "用户已被锁定");
            }
            //6补全信息

            String name = userInfo.getName();
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }

            //7登录步骤
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("name", name);
            map.put("token", token);
        } else {
            //8绑定手机号
            //8.1根据openid查询用户信息
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("openid", openid);
            UserInfo userInfo = baseMapper.selectOne(wrapper);
            if (userInfo == null) {
                throw new YyghException(20001, "用户注册信息有误");
            }
            //8.2更新用户手机号
            userInfo.setPhone(phone);
            baseMapper.updateById(userInfo);
            //5校验用户是否被锁定
            if (userInfo.getStatus() == 0) {
                throw new YyghException(20001, "用户已被锁定");
            }
            //6补全信息

            String name = userInfo.getName();
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }

            //7登录步骤
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("name", name);
            map.put("token", token);

        }
        return map;
    }

    //保存用户
    @Override
    public void saveUserInfo(Long userId, UserAuthVo userAuthVo) {
        // 先查询
        UserInfo userInfo = userInfoMapper.selectById(userId);
        if (userInfo == null) {
            throw new YyghException(20001, "用户信息有误");
        }
        // 再保存
        BeanUtils.copyProperties(userAuthVo, userInfo);
        userInfoMapper.updateById(userInfo);
    }

    //获取用户信息接口 翻译字段并返回
    @Override
    public UserInfo getUserInfo(Long userId) {
        // 查询
        UserInfo userInfo = userInfoMapper.selectById(userId);
        //翻译字段
        return this.packUserInfo(userInfo);

    }

    // 用户信息查询 带分页
    @Override
    public Page<UserInfo> selectPage(Page<UserInfo> userInfoPage, UserInfoQueryVo userInfoQueryVo) {
        //取出VO里面的条件 来进行模糊查询
        String user = userInfoQueryVo.getKeyword();
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();
        Integer status = userInfoQueryVo.getStatus();
        Integer authStatus = userInfoQueryVo.getAuthStatus();

        //2验空，拼写查询条件
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(user)){
            wrapper.like("name",user);
        }
        if(!StringUtils.isEmpty(status)) {
            wrapper.eq("status",status);
        }
        if(!StringUtils.isEmpty(authStatus)) {
            wrapper.eq("auth_status",authStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }
        //3分页查询
        Page<UserInfo> userInfoPage1 = userInfoMapper.selectPage(userInfoPage, wrapper);

        // 翻译字段
        userInfoPage1.getRecords().stream().forEach(i->{
            this.packUserInfo(i);
        });
        return userInfoPage1;

    }

    // 用户 锁定
    @Override
    public void lock(Long userId, Integer status) {
        if (status==0 || status== 1){
            UserInfo userInfo = userInfoMapper.selectById(userId);
            userInfo.setStatus(status);
            userInfoMapper.updateById(userInfo);
        }
    }

    // 详情展示用户信息、用户就诊人信息
    @Override
    public Map<String, Object> show(Long userId) {
        // 查询并翻译userinfo
        UserInfo userInfo = this.packUserInfo(userInfoMapper.selectById(userId));

        //查询出名下的就诊人
        List<Patient> patientList  = patientService.findAll(userInfo.getId());
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("userInfo",userInfo);
        hashMap.put("patientList",patientList);

        return hashMap;
    }

    @Override
    public void approval(Long userId, Integer authStatus) {
        if (authStatus==1 || authStatus==2){
            UserInfo userInfo = userInfoMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            userInfoMapper.updateById(userInfo);
        }
    }

    // 翻译字段
    private UserInfo packUserInfo(UserInfo userInfo) {
        //认证状态
        String authStatusString =
                AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus());
        userInfo.getParam().put("authStatusString",authStatusString);
        //处理用户状态 0  1
        String statusString = userInfo.getStatus()==0 ?"锁定" : "正常";
        userInfo.getParam().put("statusString",statusString);

        return userInfo;
    }
}
